<!--语单对讲 -->
<template>
  <div id="videoCallDialog" >
    <Modal v-model="modal.show"  :title="modal.title"  :mask-closable="false"
           :footer-hide=true width="1080px" :closable="false">
      <Row>
        <Col span="24">
          <div style="display: flex;height:300px">
            <div style="width:45%;height:100%;">
              <div v-show="!devicePlay.loading" style="width:100%;height:100%;background-color: #00060c">
                <audio v-show="1===0" id="deviceAudioEl" ref="deviceAudioEl" style="width:100%;height:100%" autoplay controls/>
                  <canvas id="deviceCanvasEl" ref="deviceCanvasEl" style="width:100%;height:100%;"></canvas>
              </div>
              <div v-show="devicePlay.loading" style="width:100%;height:100%;display:flex;justify-content: center;align-items: center">
                <Spin  size="large" ></Spin>
              </div>
            </div>
            <div style="width:10%;height:100%;display: flex;flex-direction: column;align-items: center;justify-content: center">
              <Button :title="h5.startTheIntercom" type="success" shape="circle" icon="md-call"  :disabled="!(!talking && deviceSupport)" @click="starTalk"></Button>
              <br>
              <br>
              <Button :title="h5.endTheIntercom" type="error" shape="circle" icon="md-call"  :disabled="!(talking && deviceSupport)" @click="stopTalk"></Button>
            </div>
            <div style="width:45%;height:100%;background-color: #0c0c0c">
              <audio v-show="1===0" id="localAudioEl" ref="localAudioEl" style="width:100%;height:100%" autoplay controls muted/>
              <canvas v-show="deviceSupport" id="localCanvasEl" ref="localCanvasEl" style="width:100%;height:100%"></canvas>
              <div v-show="!deviceSupport" style="width:100%;height:100%;display: flex;justify-content: center;align-items: center">
                <span style="font-size: 30px;color:#8ef8e7;">{{h5.deviceInitFailed}}</span>
              </div>
            </div>
          </div>
        </Col>
      </Row>
      <Row>
        <Col span="24">
          <div style="display: flex;justify-content: center">
            <Button type="primary" @click="close">{{h5.close}}</Button>
          </div>
        </Col>
      </Row>
    </Modal>
  </div>
</template>
<script>
import Device from "@/api/Device";
import MediaDevice from "@/api/MediaDevice";
import {apiResult} from "@/libs/util";
export default {
  computed:{
    h5(){
      return{
        deviceInitFailed:this.$t('device_init_failed'),
        startTheIntercom:this.$t('start_the_intercom'),
        endTheIntercom:this.$t('end_the_intercom'),
        close:this.$t('close'),
      }

    }
  },
  data(){
    return{
      api: new Device(),
      talking: false,
      deviceSupport: true,
      modal:{
        show:false,
        loading:false,
        title:this.$t("audio_call"),
      },
      devicePlay:{
        loading:true,
        audioEl:null,
        MediaStreamTrack:null,
        canvasEl:null,
        audioCtx:null,
        timer:null,
        audioRtcPlayer:null,
        playUrl:null,
      },
      localPlay:{
        audioEl:null,
        canvasEl:null,
        pushApp:"live",
        pushStream:null,
        pushUrl:null,
        audioRtcPlayer:null,
        mediaStreamTrack:null,
        mediaStream: null,
        audioCtx:null,
        timer:null,
      },
      deviceId:null,
      channelId:null,
      protocol:'rtc'
    }
  },
  methods:{
    starTalk(){
      const _this = this;
      this.api.playGbTalk(this.deviceId,this.localPlay.pushApp,this.localPlay.pushStream).then((res)=> {
        console.log(res);
          apiResult(res.data,false,result=>{
            //广播发出成功，可以推流了
            //推流
            _this.localPlay.audioRtcPlayer = new ZLMRTCClient.Endpoint({
              element: _this.localPlay.audioEl,// video 标签
              debug: false,// 是否打印日志
              zlmsdpUrl: _this.localPlay.pushUrl,//流地址
              simulecast: false,
              useCamera: false,
              audioEnable: true,
              videoEnable: false,
              recvOnly: false,
            })

            _this.localPlay.audioRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE, function (state) {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
              console.log('当前状态==>', state)
              if ("connected" === state) {
                new MediaDevice().audioWave(_this.localPlay.mediaStream, _this.localPlay.canvasEl, (res1) => {
                  console.log(res1);
                  _this.localPlay.audioCtx = res1.audioCtx;
                  _this.localPlay.timer = res1.timer;
                  _this.talking = true;
                })

              }
            });
          })
        /*if (res.data.code === 0) {
          //广播发出成功，可以推流了
          //推流
          _this.localPlay.audioRtcPlayer = new ZLMRTCClient.Endpoint({
            element: _this.localPlay.audioEl,// video 标签
            debug: false,// 是否打印日志
            zlmsdpUrl: _this.localPlay.pushUrl,//流地址
            simulecast: false,
            useCamera: false,
            audioEnable: true,
            videoEnable: false,
            recvOnly: false,
          })

          _this.localPlay.audioRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE, function (state) {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
            console.log('当前状态==>', state)
            if ("connected" === state) {
              new MediaDevice().audioWave(_this.localPlay.mediaStream, _this.localPlay.canvasEl, (res) => {
                console.log(res);
                _this.localPlay.audioCtx = res.audioCtx;
                _this.localPlay.timer = res.timer;
                _this.talking = true;
              })
/!*              const constraints = {audio: true};
              navigator.mediaDevices.getUserMedia(constraints).then(function (mediaStream) {
                //关闭 MIC使用
                _this.localPlay.mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[0];
                //音频波形图
                new MediaDevice().audioWave(mediaStream, _this.localPlay.canvasEl, (res) => {
                  console.log(res);
                  _this.localPlay.audioCtx = res.audioCtx;
                  _this.localPlay.timer = res.timer;
                  _this.talking = true;
                })
              }).catch((err) => {
                console.log("getUserMedia: %o",err);
                _this.$Message.error(err);
              })*!/
            }
          });
        }else{
          _this.$Message.error(res.data.msg);
        }*/
      }).catch((err)=>{
        console.log(err);
      })
    },
    stopTalk(){
      if (this.talking){
        if(this.localPlay.audioRtcPlayer){
          this.localPlay.audioRtcPlayer.close();
          this.localPlay.audioRtcPlayer = null;
          if(!!this.localPlay.audioEl){
            this.localPlay.audioEl.srcObject = null;
            this.localPlay.audioEl.load();
          }
        }

        this.api.stopGbTalk(this.deviceId,this.localPlay.pushApp,this.localPlay.pushStream).then((res)=>{
          apiResult(res.data,false,result=>{
            this.$Message.info(this.$t('intercom_stoped'));
          });
        })

        this.talking = false;
        if (!!this.localPlay.audioCtx){
          this.localPlay.audioCtx.close();
          this.localPlay.audioCtx=null;
        }

        if (!!this.localPlay.timer){
          clearInterval(this.localPlay.timer)
          this.localPlay.timer=null;
        }
      }
      this.talking = false;

    },
    openDialog: function (deviceId, channelId) {
      //console.log("openDialog")
      this.stop();
      this.devicePlay.loading = true;
      this.deviceId = deviceId;
      this.channelId = channelId;
      this.localPlay.pushApp="live";
      this.localPlay.pushStream = deviceId + "_" + channelId + "_gbtalk";
      let pushUrl = "http://192.168.0.129:8080/index/api/webrtc?app=live&stream=" + this.localPlay.pushStream + "&type=push";
      this.localPlay.pushUrl = this.api.getPushUrl(pushUrl);

      this.modal.show=true;
      this.getPlayUrl().then(()=>{
      },(err)=>{
        this.$Message.error(err);
      })

      const _this = this;
      const constraints = { audio: true};
      navigator.mediaDevices.getUserMedia(constraints).then(function(mediaStream) {
        //console.log(">>>>>>>>>> getUserMedia成功！")
        //关闭 MIC使用
        //_this.MediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[0];
        _this.localPlay.mediaStreamTrack = typeof mediaStream.stop === 'function' ? mediaStream : mediaStream.getTracks()[0];
        _this.localPlay.mediaStream = mediaStream;
        _this.deviceSupport = true;
      }).catch((err)=>{
        //console.log(">>>>>>>>>> getUserMedia失败 %o！",err);
        _this.$Message.error(this.$t('device_init_failed'));
        _this.deviceSupport = false;
      })
    },
    getPlayUrl(){
      //console.log("getPlayUrl")
      return new Promise((resolve, reject) => {
        this.api.playStart(this.deviceId,this.channelId).then(res=> {
          apiResult(res.data,false,result=>{
            if (!!result.data[this.protocol]) {
              const playUrl = result.data[this.protocol];
              this.devicePlay.playUrl=this.api.getPlayUrl(playUrl);
              //console.log("playUrl111=%o",this.devicePlay.playUrl)
              this.playInit();
              resolve()
            }
          })
        }).catch(err => {
          reject(err)
        })
      });
    },
    close: function(){
      this.stop();
      this.modal.show = false;
    },
    playInit(){
      this.devicePlay.audioRtcPlayer = null;
      const _this = this;
      this.devicePlay.audioRtcPlayer = new ZLMRTCClient.Endpoint({
        element: this.devicePlay.audioEl,// video 标签
        debug: false,// 是否打印日志
        zlmsdpUrl: _this.devicePlay.playUrl,//流地址
        simulecast: true,
        useCamera: true,
        audioEnable: true,
        videoEnable: false,
        recvOnly: true,

      })
      //播放成功
      this.devicePlay.audioRtcPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS,(e)=>{//获取到了远端流，可以播放
        console.log('播放成功: %o',e);
        _this.devicePlay.loading = false;
      });
    },
    stop(){
      this.stopTalk();
      if(!!this.devicePlay.audioRtcPlayer)
      {
        this.devicePlay.audioRtcPlayer.close();
        this.devicePlay.audioRtcPlayer = null;
        if(!!this.devicePlay.audioEl)
        {
          this.devicePlay.audioEl.srcObject = null;
          this.devicePlay.audioEl.load();
        }
      }

      console.log("devicePlay.audioCtx=%o",this.devicePlay.audioCtx)
      if (!!this.devicePlay.audioCtx){
        this.devicePlay.audioCtx.close();
        this.devicePlay.audioCtx=null;
      }

      if (!!this.devicePlay.timer){
        clearInterval(this.devicePlay.timer)
        this.devicePlay.timer=null;
      }
      this.devicePlay.MediaStreamTrack && this.devicePlay.MediaStreamTrack.stop();
      this.localPlay.mediaStreamTrack && this.localPlay.mediaStreamTrack.stop();
    },
  },
  mounted() {
    const _this = this;
    const isHttps = 'https:' === document.location.protocol;
    this.protocol = isHttps?"rtcs":"rtc";
    this.$nextTick(()=>{
      _this.devicePlay.audioEl = this.$refs.deviceAudioEl;
      _this.devicePlay.canvasEl = this.$refs.deviceCanvasEl;

      _this.localPlay.audioEl = this.$refs.localAudioEl;
      _this.localPlay.canvasEl = this.$refs.localCanvasEl;

      //_this.audioElement = _this.$refs.audioPlayer1;
      _this.devicePlay.audioEl.addEventListener("loadedmetadata", (res)=> {
        //console.log("loadedmetadata");
        //关闭 MIC使用
        const mediaStream = _this.devicePlay.audioEl.srcObject;
        _this.devicePlay.MediaStreamTrack=typeof mediaStream.stop==='function'?mediaStream:mediaStream.getTracks()[0];
        //画音频波形
        new MediaDevice().audioWave(mediaStream,_this.devicePlay.canvasEl,
          (res)=>{
            console.log(res);
            _this.devicePlay.audioCtx = res.audioCtx;
            _this.devicePlay.timer = res.timer;
          })
      })
    });
  }
}
</script>
